package com.yc.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.study.entity.User;
import com.yc.study.service.IAnswerSheetService;
import com.yc.study.service.IJobService;
import com.yc.study.service.IUserService;
import com.yc.study.vo.AnswerSheetVo;
import com.yc.study.vo.JobVo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 前端控制器
 *
 * @author 王妍
 * @since 2022-02-20
 */
@RestController
@RequestMapping("/study/job")
@AllArgsConstructor
public class JobController {
  private final IJobService jobService;
  private final IUserService userService;
  private final IAnswerSheetService answerSheetService;

  @PostMapping
  public void createJob(Principal principal, @RequestBody JobVo job) {
    String username = principal.getName();
    jobService.saveJob(job, username);
  }

  /**
   * 通过课程id查询作业列表
   *
   * @param courseId 课程id
   */
  @GetMapping("/course/{courseId}")
  public Page<JobVo> getJobPage(Page<JobVo> jobVoPage, @PathVariable("courseId") Long courseId) {
    return jobService.loadPageVoByCourseId(jobVoPage, courseId);
  }

  @GetMapping("page")
  public Page<JobVo> getJobPageByTeacher(Principal principal, Page<JobVo> page, JobVo jobVo) {
    final String username =
        Optional.ofNullable(principal.getName()).orElseThrow(() -> new RuntimeException("用户未登录！！"));
    final User user =
        Optional.ofNullable(userService.loadUserByUserName(username))
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    jobVo.setTeacherId(user.getId());
    return jobService.loadPageVoByTeacherId(page, jobVo);
  }
  /** 查询学生的作业列表 */
  @GetMapping("/student")
  public Page<JobVo> getJobPage(Page<JobVo> jobVoPage, Principal principal) {
    final String username =
        Optional.ofNullable(principal.getName()).orElseThrow(() -> new RuntimeException("用户未登录！！"));
    final User user =
        Optional.ofNullable(userService.loadUserByUserName(username))
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    return jobService.loadPageVoByStudentId(jobVoPage, user.getId());
  }

  @DeleteMapping
  public void delete(@RequestBody Long[] jobIds) {
    jobService.deleteJobs(Arrays.asList(jobIds));
  }

  /** 交卷 */
  @PostMapping("finishUpJob")
  public Long finishUpJob(Principal principal, @RequestBody List<AnswerSheetVo> answerSheetVos) {
    // 获取用户信息
    final String username =
        Optional.ofNullable(principal.getName()).orElseThrow(() -> new RuntimeException("用户未登录！！"));
    final User user =
        Optional.ofNullable(userService.loadUserByUserName(username))
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    return answerSheetService.save(user.getId(), answerSheetVos);
  }
}
